package com.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@WebServlet("/DownLoadServlet")
public class DownLoadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {

        String clientFileName = req.getParameter("filename");
        String Referer = req.getHeader("Referer");
        if (!Referer.equals("http://localhost:8081/")) {
            return;
        }

        //设置http的响应头
        if (clientFileName.endsWith("zip")) {
            response.setHeader("Content-Type", "application/octet-stream");//告诉客户端服务返回的内容是二进制流数据
        } else if (clientFileName.endsWith("pdf")) {
            response.setHeader("Content-Type", "application/pdf");
        } else if (clientFileName.endsWith("docx")) {
            response.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        }
        //text/html  //告诉客户端 服务端返回的内容是text/html文档
        //application/msword  //告诉客户端，返回的内容是一个word文件，浏览器会打开本地的word工具来显示服务端返回的内容
        //application/pdf

        //Content-Disposition: attachment;filename=aaa.zip：服务器通过这个头告诉浏览器，以下载方式打开数据

        //客户端就会打开浏览器的下载器下下载文件
        //等价于
        // response.setHeader("Content-Type","text/html;charset=utf-8");
        //response.setContentType("text/html;charset=utf-8");

        //在服务器上读取电脑中的某个文件 ，将文件内容发送给客户端
        File file = new File("E:\\书籍\\200本后端必备电子书\\" + clientFileName);
        //下载的文件名中有中文，中文被忽略了
        //需要对文件名进行转码，转成ISO-8859-1的编写

        //转码的过程： 先得到字符串对应的字节数组-->再用newString方法将字节数组转换为字符串
        String fileName = file.getName();
        System.out.println("转码前的文件名为:" + fileName);
        fileName = new String(fileName.getBytes(), "iso-8859-1"); //解决浏览器中文乱码问题
        System.out.println("转码后的文件名为:" + fileName);

        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);//设置下载的文件名称

        FileInputStream fileInputStream = new FileInputStream(file);

        byte[] buf = new byte[1024];
        int len = 0;
        OutputStream outputStream = response.getOutputStream();
        while ((len = fileInputStream.read(buf)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
    }
}
